package app.monitor;

import java.util.Date;
import java.util.TimerTask;

import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.SigarException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

import app.htby.utils.IOTSUtils;
import app.htby.utils.KafkaUtils;
import app.htby.utils.SpringContextUtil;
import app.kafka.produce.HTBYKafkaProducer;

/**
 * 系统资源监控的timer
 * 
 * @author lfy.xys
 * @date 2018年5月2日
 *
 */
public class MonitorTimer extends TimerTask {

	private static Logger logger = LoggerFactory.getLogger(MonitorTimer.class);

	@Override
	public void run() {
		logger.info("开始执行timer");
		try {
			MonitorController monitorCtrl = new MonitorController();
			//设置时间
			IOTSUtils.iotsSystemMonitor.setCreateTime(new Date());
			
			// 设置内存属性
			monitorCtrl.setPhysicalMemory();
			// 设置cpu个数
			monitorCtrl.setCpuCount();
			// 设置cpu属性
			CpuPerc[] cpuList = monitorCtrl.setCpuPerc();

			for (int i = 0; i < cpuList.length; i++) {
				String cpuUsed = CpuPerc.format(cpuList[i].getCombined());
				
				IOTSUtils.iotsSystemMonitor.setCpuId(i+1);
				IOTSUtils.iotsSystemMonitor.setCpuUsed(cpuUsed);
				
				// json化bean
				String jsonStr = JSONObject.toJSONString(IOTSUtils.iotsSystemMonitor);
				logger.info(jsonStr);

				HTBYKafkaProducer sender = SpringContextUtil.getApplicationContext().getBean(HTBYKafkaProducer.class);
				sender.send(KafkaUtils.monitor_topic, jsonStr);
			}

		} catch (SigarException e) {
			e.printStackTrace();
		}
		

	}

}
